package LeetCode.exercise;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class LC1419 {
    public static void main(String[] args) {
        System.out.println(minNumberOfFrogs("crroakcoak"));
    }
    public static int minNumberOfFrogs(String croakOfFrogs) {
        char[] chars = new char[]{'c','r','o','a','k'};
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < croakOfFrogs.length(); i++) {
            char ch1 = croakOfFrogs.charAt(i);
            if(ch1 == 'c') {
                if (hashMap.containsKey('k') && hashMap.get('k') != 0) {
                    hashMap.put('k', hashMap.get('k') - 1);
                }
                hashMap.put('c', hashMap.getOrDefault('c', 0) + 1);
            } else {
                int index = 0;
                for (int j = 0; j < chars.length; j++) {
                    if(ch1 == chars[j]){
                        index = j-1;
                        break;
                    }
                }
                char ch2 = chars[index];
                if(hashMap.containsKey(ch2)){
                    hashMap.put(ch2, hashMap.getOrDefault(ch2,0)-1);
                    if(hashMap.get(ch2) < 0){
                        return -1;
                    }
                    hashMap.put(ch1, hashMap.getOrDefault(ch1, 0)+1);
                } else {
                    return -1;
                }
            }
        }
        Iterator<Map.Entry<Character, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Character, Integer> next = iterator.next();
            if(next.getValue() != 0 && next.getKey() != 'k'){
                return -1;
            }
        }
        return hashMap.get('k');
    }
}
